package com.oig.sys.msg.controller;


import com.oig.common.exception.BadRequestException;
import com.oig.common.module.SysResponse;
import com.oig.common.validator.GroupAdd;
import com.oig.common.validator.GroupComplete;
import com.oig.common.validator.GroupEdit;
import com.oig.sys.log.annotation.SysLog;
import com.oig.sys.msg.dto.TaskDto;
import com.oig.sys.msg.service.ITbTaskService;
import com.oig.sys.msg.vo.TaskVo;
import com.oig.sys.security.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Tag(name = "任务管理")
@RestController
@RequestMapping("/task")
@Slf4j
@RequiredArgsConstructor
public class TbTaskController {

    private final ITbTaskService taskService;

    //登录用户都有权限加
    //@PreAuthorize("@pms.hasPermission('/task/add')")
    @SysLog(value="添加任务",apiUrl="/task/add")
    @Operation(summary = "添加任务")
    @PostMapping(value = "/add")
    public TaskVo addTask(@RequestBody @Validated(GroupAdd.class) TaskDto taskDto){
        log.info("add task, {}", taskDto);
        if (taskDto.getWatchId()==null){	//不是系统加的任务，人为加的任务，那么默认添加人为跟踪人
            if (SecurityUtil.getUser()==null){
                throw new BadRequestException("没有跟踪人") ;
            }
            taskDto.setWatchId(SecurityUtil.getDefineUserMain().getId());
            taskDto.setWatchName(SecurityUtil.getDefineUserMain().getRealName());
        }
        if (taskDto.getTenantId()==null){		//系统创建的任务 tenantId一定要传的。
            if (SecurityUtil.getUser()==null){
                throw new BadRequestException("系统创建任务， tenantId必填") ;
            }
            taskDto.setTenantId(SecurityUtil.getDefineUserMain().getTenantId());
            taskDto.setTenantName(SecurityUtil.getDefineUserMain().getTenantName());
        } else {
            if (SecurityUtil.getUser()!=null){
                SecurityUtil.getDefineUserMain().checkTenantPermission(taskDto.getTenantId());
            }
        }
        taskDto.setCreateUserId(SecurityUtil.getUserForIfNullBuild().getId());
        taskDto.setCreateUserName(SecurityUtil.getUserForIfNullBuild().getRealName());
        taskDto.setCreateTime(new Date());
        return this.taskService.addTask(taskDto);
    }

    private TaskVo checkRole(Integer taskId){
        TaskVo task = this.taskService.getTaskMainInfo(taskId);
        if (task==null){
            throw new BadRequestException("任务不存在") ;
        }
        SecurityUtil.getDefineUserMain().checkTenantPermission(task.getTenantId());
        return task;
    }

    //@PreAuthorize("@pms.hasPermission('/task/update')")
    @SysLog(value="修改任务",apiUrl="/task/update")
    @Operation(summary = "修改任务")
    @PostMapping(value = "/update")
    public TaskVo updateTask(@RequestBody @Validated(GroupEdit.class) TaskDto taskDto){
        log.info("update task, {}", taskDto);
        TaskVo task = this.checkRole(taskDto.getId());
        if (!SecurityUtil.getDefineUserMain().getId().equals(task.getCreateUserId())
                &&!SecurityUtil.getDefineUserMain().getId().equals(task.getDealId())
                &&!SecurityUtil.getDefineUserMain().getId().equals(task.getWatchId())){
            throw new BadRequestException("无权修改") ;
        }
        taskDto.setLastUpdateId(SecurityUtil.getUserForIfNullBuild().getId());
        taskDto.setLastUpdateName(SecurityUtil.getUserForIfNullBuild().getRealName());
        taskDto.setLastUpdateTime(new Date());
        return this.taskService.updateTask(taskDto);
    }

    //@PreAuthorize("@pms.hasPermission('/task/del')")
    @SysLog(value="物理删除任务",apiUrl="/task/del")
    @Operation(summary = "物理删除任务")
    @PostMapping(value = "/del/{taskId}")
    public SysResponse<Integer> delTask(@PathVariable("taskId") Integer taskId){
        log.info("delete task id={}", taskId) ;
        TaskVo task = this.checkRole(taskId);
        if (!SecurityUtil.getDefineUserMain().getId().equals(task.getCreateUserId())
                &&!SecurityUtil.getDefineUserMain().getId().equals(task.getWatchId())){
            throw new BadRequestException("无权删除") ;
        }
        this.taskService.deleteTask(taskId);
        return SysResponse.ok(taskId,"物理删除成功");
    }

    /**
     * 关闭任务
     */
    @SysLog(value="关闭任务",apiUrl="/task/close")
    @Operation(summary = "关闭任务")
    @PostMapping(value = "/close")
    public SysResponse<String> closeTask(@RequestBody @Validated(GroupComplete.class) TaskDto taskDto){
        log.info("{}, close task: {}", SecurityUtil.getDefineUserMain().getRealName(), taskDto) ;
        this.checkRole(taskDto.getId()) ;
        taskDto.setLastUpdateId(SecurityUtil.getUserForIfNullBuild().getId());
        taskDto.setLastUpdateName(SecurityUtil.getUserForIfNullBuild().getRealName());
        taskDto.setLastUpdateTime(new Date());
        this.taskService.closeTask(taskDto);
        return SysResponse.ok("关闭任务");
    }

    /**
     * 打开任务
     */
    @SysLog(value="打开任务",apiUrl="/task/open")
    @Operation(summary = "打开任务")
    @PostMapping(value = "/open")
    public SysResponse<String> openTask(@RequestBody @Validated(GroupComplete.class) TaskDto taskDto){
        log.info("{}, open task: {}", SecurityUtil.getDefineUserMain().getRealName(), taskDto) ;
        this.checkRole(taskDto.getId());
        taskDto.setLastUpdateId(SecurityUtil.getUserForIfNullBuild().getId());
        taskDto.setLastUpdateName(SecurityUtil.getUserForIfNullBuild().getRealName());
        taskDto.setLastUpdateTime(new Date());
        this.taskService.openTask(taskDto);
        return SysResponse.ok("打开任务");
    }

    @Operation(summary = "任务详细信息")
    @PostMapping(value = "/info/{taskId}")
    public TaskVo getTask(@PathVariable("taskId") Integer taskId){
        log.info(" get task id=:{}", taskId);
        this.checkRole(taskId);
        return this.taskService.getTask(taskId);
    }


}
